//201902104030_何琛选
package cn.edu.sdjzu.xg.bysj.service;

import cn.edu.sdjzu.xg.bysj.dao.CommonDao;
import cn.edu.sdjzu.xg.bysj.dao.ProfTitleDao;
import cn.edu.sdjzu.xg.bysj.domain.ProfTitle;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;
import util.bysjException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class ProfTitleService {
	private static ProfTitleDao profTitleDao= ProfTitleDao.getInstance();
	private static ProfTitleService profTitleService=new ProfTitleService();
	private ProfTitleService(){}

	public static ProfTitleService getInstance(){
		return profTitleService;
	}

	public Collection<ProfTitle> findAll(
			List<Condition> conditionList_json_str, Pagination pagination)
			throws SQLException {
		//获得链接以便完成可能的事务操作
		Connection connection = JdbcHelper.getConn();
		Collection<ProfTitle> profTitles = profTitleDao.findAll(
				connection,conditionList_json_str,pagination);
		JdbcHelper.close(connection);
		return profTitles;
	}

	public ProfTitle find(Integer id) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		ProfTitle profTitle = profTitleDao.find(id,connection);
		JdbcHelper.close(connection);
		return profTitle;
	}

	public boolean update(ProfTitle profTitle) throws SQLException {
		boolean result = false;
		Connection connection = JdbcHelper.getConn();
		result = profTitleDao.update(profTitle,connection);
		JdbcHelper.close(connection);
		return result;
	}

	public boolean add(ProfTitle profTitle) throws SQLException {
		boolean result = false;
		Connection connection = JdbcHelper.getConn();
		result = profTitleDao.add(profTitle,connection);
		JdbcHelper.close(connection);
		return result;
	}

	public boolean delete(Integer id) throws SQLException,bysjException {
		boolean result = false;
		Connection connection = JdbcHelper.getConn();
		result = this.delete(this.find(id));
		JdbcHelper.close(connection);
		return result;
	}

	public boolean delete(ProfTitle profTitle) throws SQLException,bysjException {
		boolean result = false;
		Connection connection = JdbcHelper.getConn();
		//获得所有下一级单位
		int countTeacherOfDepartment = CommonDao.getInstance().
				countWhereForeignKey(
						connection,
						"teacher",
						"profTitle_id",
						profTitle.getId());
		//若没有二级单位，则能够删除
		if(countTeacherOfDepartment==0){
			result = profTitleDao.delete(profTitle,connection);
		}else {
			throw new bysjException(profTitle.getDescription()+"有下属系，不能删除");
		}
		JdbcHelper.close(connection);
		return result;
	}
}

